package com.slicktechnologies.server;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.google.appengine.api.datastore.ReadPolicy.Consistency;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.Query;
import com.simplesoftwares.client.library.ReturnFromServer;
import com.simplesoftwares.client.library.appstructure.SuperModel;
import com.simplesoftwares.client.library.appstructure.search.MyQuerry;
import com.slicktechnologies.client.services.CompanyRegistrationService;
import com.slicktechnologies.shared.common.businessunitlayer.Company;
import com.slicktechnologies.shared.common.helperlayer.User;

public class CompanyRegistrationServiceImpl extends RemoteServiceServlet implements CompanyRegistrationService{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8028459064515281201L;

	@Override
	public ReturnFromServer saveCompany(Company company) {
		//Set the count of Company

		if(company.getCount()==0)
	    {
	    	int count=ofy().load().type(company.getClass()).count();
	    	company.setCount(count+1);
	    	
	    }
		//Check weather company id is null , then only save it for first time.
		if(company.getId()==null)
		{
			//To check weather acess url already exists or not
			int count=ofy().load().type(Company.class).filter("accessUrl", company.getAccessUrl()).count();
			if(count!=0)
				return null;
			//To check weather company name already exists or not
			int countCompany=ofy().load().type(Company.class).filter("buisnessUnitName", company.getBusinessUnitName()).count();
			if(countCompany!=0)
				return null;
			//Save the company it is being saved for first time set its id
			ofy().save().entity(company).now();
			company.setCompanyId(company.getId());
			ofy().save().entity(company).now();
			//Create a default user
			User user=new User();
			String temp=company.getBusinessUnitName().trim().replaceAll("\\s","");
			temp=temp.toLowerCase();
			user.setUserName("admin123");
			user.setPassword("pass123");
			//Set a default role to user
			
			
			
			//save user
			user.setCompanyId(company.getId());
			
			user.setStatus(true);
			ofy().save().entity(user).now();
			//save role
			
			
			//send email
			sendEmail(company);
		}
		else
			ofy().save().entity(company).now();
		
		 ReturnFromServer server = new ReturnFromServer();
		 server.id=company.getId();
		  server.count=company.getCount();
		  sendEmail(company);
		 return server;
	    
	}
	
	public void sendEmail(Company c) {
		Properties props = new Properties();
		  Logger logger = Logger.getLogger("NameOfYourLogger");
	      
        Session session = Session.getDefaultInstance(props, null);
        String name=c.getPocName();
        name=name.replace("null", "");
        String userid="admin123";
        userid=userid.replaceAll("\\s","");
        userid=userid.trim();
        userid=userid.toLowerCase();
       
        String password="pass123";
        password=password.replaceAll("\\s","");
        password=password.toLowerCase();
        password=password.trim();
        
        //Calculation of End date
        int planDurationinDay=c.getNoOfWeeks()*7;
        Date startDate=c.getLicenseStartDate();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate); // Now use today date.
        calendar.add(Calendar.DATE, planDurationinDay); // Adding 5 days
        String planEnd = sdf.format(calendar.getTime());
        String start=sdf.format(startDate);
        String CompnayMessage="";
        if(c.getStatus().equals(Company.DEMO))
        CompnayMessage="Thanks for asking evaluation copy. We are confident that this will be "
            		+ "enormous value addition to your business.<br><br><br>";
        if(c.getStatus().equals(Company.ACTIVE))
        	CompnayMessage="Thanks for choosing EVA Software Solutions to manage your business operations"+
                     "We are confident that this will be enormous value addition to your business.<br><br><br>";
       

        String msgBody = ""
        		+ "Dear "+name+","+"<br>"
        		+ "Greetings from EVA Software Solution!"+"<br>"
        		+CompnayMessage
        		+ "<b>Your account details are :</b>"+"<br><br><br>"
        		+"User ID :&nbsp;&nbsp; "+userid+"<br>"
        		+"Password :&nbsp;&nbsp; "+password+"<br>"
        		+"Account status  :&nbsp;&nbsp; "+c.getStatus()+"<br>"
        		+ "License Start Date :&nbsp;"+start+"<br>"
        		+ "License End Date :&nbsp;&nbsp;"+planEnd+"<br>"
        		+"No. of Users :&nbsp;"+c.getNoOfUser()+"<br><br><br>"
        		+"Link to access your EVA ERP / CRM : "+c.getAccessUrl()+".evasoftwaresolutions.appspot.com"+"<br><br><br>"
        		+ "For any queries, please contact us at the touch points mentioned below and we will be happy to assist you.Or"
        		+ " Call us on "+"+91919619390370 "+","
        		+ " email us at "+"support@evasoftwaresolutions.com"+"."+"<br><br><br> "
        		+"For any online assistance required please refer user guides at  link"
        		+"<a href=www.evasoftwaresolutions.com/download.html> User Guide </a><br><br><br>"
        		+ " We value your association with us and assure you of our best services.<br><br><br>"
        		+ "<b>"+"EVA Software Solutions"+"</b><br><br>"
                +"# 1 , Monginis Cake Shop<br>"
                +"<b>Station Road, Hariyalli Village</b> <br>"
                +"<b>Tagore Nagar</b> <br>"
                +"<b>Vikhroli East</b> <br>"
                +"<b>Mumbai 400083</b> <br>"
                +"<b>email - sales@evasofotwaresolutions.com </b> <br>"
                +"<b>website - www.evasoftwaresolutions.com</b> <br>"
                +"<b>Phone - +91 9619390370 / +91 (0)22 25740698</b> <br>"
                ;
                
        

        try {
            Message msg = new MimeMessage(session);
            String website=c.getWebsite();
            if(website!=null || website.trim().equals("")==false)
            msg.setFrom(new InternetAddress("evasoftwaresolutions@gmail.com","Eva Software Solution"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(c.getEmail(),name));
           msg.setSubject("New Company Registration");
            Multipart mp=new MimeMultipart();
	          
	          MimeBodyPart htmlpart=new MimeBodyPart();
	          htmlpart.setContent(msgBody,"text/html");
	          mp.addBodyPart(htmlpart);
	          msg.setContent(mp);
         Transport.send(msg);

        } catch (Exception e) {
        	e.printStackTrace();
            // ...
        
	}
		
	}
	
	
	@Override
	   public ArrayList<SuperModel> getSearchResult(MyQuerry quer)
	   {
		   //Clear the session
		   ArrayList<SuperModel> list=new ArrayList<SuperModel>();
		   try{
		   ofy().clear();
		   Query<? extends SuperModel> query = null;
		   //Get the querry
		   query=ofy().load().type(quer.getQuerryObject().getClass());
		   Logger logger = Logger.getLogger("NameOfYourLogger");
		     //Get the 
		   if(quer.getFilters()!=null)
			{
		      for(int i=0;i<quer.getFilters().size();i++)
				{
				      String conditionField=quer.getFilters().get(i).getQuerryString();
				     
				      Object value=quer.getFilters().get(i).geFilterValue();
				    
				      if(value instanceof Date)
				        {
				    	  
				    	  logger.log(Level.SEVERE,"Condition Field "+conditionField);
					        logger.log(Level.SEVERE,"Condition Value "+value);
					        logger.log(Level.SEVERE,"Size of Querry "+query.count());
					        GWT.log("Condition Field "+conditionField);
					        GWT.log("Condition Value "+value);
				    	  logger.log(Level.SEVERE,"Condition Value before parsed "+value.toString());
				    	  Date condDate=GenricServiceImpl.parseDate((Date) value);
				    	 // Very dangerous patch learn internationalization and recode
				    	 Calendar c = Calendar.getInstance(); 
				    	 c.setTime(condDate); 
				    	 c.add(Calendar.DATE, 1);
				    	 condDate = c.getTime();
				    	 condDate= GenricServiceImpl.parseDate((Date) condDate);
				    	 logger.log(Level.SEVERE,"Condition Value When parsed "+condDate);
				    	 logger.log(Level.SEVERE,"Condition Field When parsed "+conditionField);
				    	 query=query.filter(conditionField,condDate);
				    	}
				      else
				      {
				    	    
				           
				           logger.log(Level.SEVERE,"Condition Field "+conditionField);
					        logger.log(Level.SEVERE,"Condition Value "+value);
					        if(conditionField.equals("companyId")==false)
					           query=query.filter(conditionField,value);
					        logger.log(Level.SEVERE,"Size of Querry "+query.count());
				        
				      }
				        
				      
				       
				       
			}
		      
			}    
		      ObjectifyService.reset();
		      ofy().consistency(Consistency.STRONG);
		      logger.log(Level.SEVERE,"Size of Querry "+query.count());
		      logger.log(Level.SEVERE,"Type Of"+quer.getQuerryObject().getClass());
		      
			   ofy().clear();
				for(SuperModel i:query)
					    list.add(i);
		   }
		   catch(Exception e)
		   {
			   e.printStackTrace();
		   }
		      	
			
		return list;
	   }

}
